<template>
  <div class="viewer" v-if="props.visible" ref="viewerRef">
    <div v-if="props.type === 'image'" class="viewer-box">
      <viewer :images="[pics]">
        <div class="close" @click="$emit('close')">
          <span>X</span>
        </div>

        <img :src="pics" class="fit-image" />
      </viewer>
    </div>
    <div v-else-if="props.type === 'pdf'" class="viewer-box">
      <div>
        <div class="close" @click="$emit('close')">
          <span>X</span>
        </div>
        <iframe :src="pics" ref="pdfIframe" style="width: 100%; height: 100%"></iframe>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts" name="FilePreview">
import { PublicInterface } from '@/interface/public';

export interface FilePreviewProps {
  visible: boolean;
  pics: string;
  type: PublicInterface.PublicType['filePreviewType'];
}

const props = withDefaults(defineProps<FilePreviewProps>(), {
  visible: false,
  type: 'image',
  pics: ''
});

const viewerRef = ref<HTMLElement>();

let $emit = defineEmits(['close']);

// 添加和移除事件监听器
onMounted(() => {
  window.addEventListener('click', handleOutsideClick);
});

onUnmounted(() => {
  window.removeEventListener('click', handleOutsideClick);
});

// 处理点击事件
const handleOutsideClick = (event: MouseEvent) => {
  console.log('target');

  const target = event.target as HTMLElement;

  if (!viewerRef.value?.contains(target) && !target.classList.contains('viewer-transition')) {
    $emit('close');
  }
};
</script>
<style lang="scss" scoped src="./index.scss"></style>
<style lang="scss">
.viewer-container {
  z-index: 999999 !important;
}
</style>
